<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-row>
              <a-col :span = "24">
            <a-form-model-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="请输入编号"></a-input>
            </a-form-model-item>
            <a-form-model-item label="自动生成" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-switch v-model="switchValue" @change="handleSwitchChange" />
            </a-form-model-item>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="规格" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="noneSpec">
              <a-input v-model="model.noneSpec" @change="noneSpecChange" placeholder="xxxKG*数字格式填写"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="包装规格(g)" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-model="model.packSpec" :min="1" placeholder="请输入包装规格(g)" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="库存数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inventoryQuantity">
              <a-input-number v-model="model.inventoryQuantity" placeholder="请输入库存数量" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="安全库量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="stockQuantity">
              <a-input-number v-model="model.stockQuantity" :min="0" placeholder="请输入安全库量" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="客户物料编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customCode">
              <a-input v-model="model.customCode" placeholder="请输入客户物料编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="计量单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="meUnit">
              <j-dict-select-tag type="list" v-model="model.meUnit" dictCode="ji_unit" placeholder="请选择计量单位"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="辅助单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-model="model.auUnit" dictCode="zl_unit" placeholder="请选择辅助单位"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="换算率" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="coRate">
              <a-input v-model="model.coRate" disabled placeholder="请输入换算率"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="物料分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="classificationId">
              <j-dict-select-tag type="list" v-model="model.classificationId"
                                 dictCode="erp_goods_classification,name,id" placeholder="请选择物料分类"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="物料种类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryCode">
              <j-select-goods-category ref="selectGoodsCategory" v-model="model.categoryCode"
                                       @onGoodsCategorySelected="onGoodsCategorySelected"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="所属仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouseCode">
              <erp-warehouse ref="erpWarehouse" v-model="model.warehouseCode"
                             @onWarehouseSelected="onWarehouseSelected"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="是否有版样" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isPattern">
              <j-dict-select-tag type="list" v-model="model.isPattern" dictCode="yes_no" placeholder="请选择是否有版样"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="是否关联包材" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isAssBc">
              <j-dict-select-tag type="list" v-model="model.isAssBc" dictCode="yes_no" placeholder="请选择是否关联包材" @change="onChangeShowRow"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="是否公用" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isPublic">
              <j-dict-select-tag type="list" v-model="model.isPublic" dictCode="yes_no" placeholder="请选择是否公用"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="是否领料" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isUse">
              <j-dict-select-tag type="list" v-model="model.isUse" dictCode="yes_no" placeholder="请选择是否领料"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status">
              <j-dict-select-tag type="list" v-model="model.status" dictCode="erp_status" placeholder="请选择状态"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="材质" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialQuality">
              <a-input v-model="model.materialQuality" placeholder="请输入材质" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="包材种类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packageType">
              <j-dict-select-tag type="list" v-model="model.packageType" dictCode="bc_type" placeholder="请选择包材种类" />
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="12">-->
<!--            <a-form-model-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplierId">-->
<!--              <j-dict-select-tag type="list" v-model="model.supplierId"-->
<!--                                 dictCode="erp_supplier,name,id" placeholder="请选择供应商"/>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="textareaLabelCol" :wrapperCol="textareaWrapperCol" prop="remark">
              <a-textarea v-model="model.remark" rows="4" placeholder="请输入备注"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <!-- 子表单区域 -->
        <a-row v-if="showRow">
          <!-- 新增 -->
          <a-col :span="24">
            <a-button
              type="primary"
              icon=""
              size="small"
              @click="addMaterielPackage">
              新增包材
            </a-button>
            <erp-goods-list-model ref="selectGoodsList"
                                  :modalWidth="modalWidth"
                                  :category="category"
                                  @goodsOk="goodsOk"
                                  checkval='checkbox'>
            </erp-goods-list-model>
          </a-col>
        <a-col :span="24">
          <!-- 表格 -->
          <a-table bordered :data-source="model.erpGoodsPackageList"
                   :columns="materielColumns"
                   :rowKey="record=>record.id"
                   :pagination="false">
            <template slot="num" slot-scope="text, record">
              <editable-cell :text="text" @change="onCellChange(record, 'num', $event)"></editable-cell>
            </template>
            <template slot="operation" slot-scope="text, record">
              <a-popconfirm
                title="确认删除?"
                @confirm="() => onDelete(record.packageId)"
              >
                <a href="javascript:;">删除</a>
              </a-popconfirm>
              <!--                <a @click="handleEdit(record)">保存</a>-->
            </template>
          </a-table>
        </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import {httpAction} from '@/api/manage'
import {putAction} from '@api/manage'
import {postAction} from '@api/manage'
import {getAction} from '@api/manage'
import Big from 'big.js';
import ErpGoodsListModel from "@comp/base/modal/ErpGoodsListModal";
import EditableCell from '@comp/table/EditableCell'

export default {
  name: 'ErpGoodsForm',
  components: {
    ErpGoodsListModel,EditableCell
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      switchValue:false,
      modalWidth: 1250,
      category: '2',
      showRow: false,
      categoryName: '',
      model: {
        id:'',
        code: '',
        status: 1,
        isUse: 1,
        isPublic: 1,
        isAssBc: 1,
        isPattern: 1,
        coRate: 0,
        packageType: '',
        materialQuality: '',
        erpGoodsPackageList: []
      },
      materielColumns: [
        {
          title: '包材编号',
          dataIndex: 'packageCode',
        },
        {
          title: '包材名称',
          dataIndex: 'packageName',
        },
        {
          title: '规格型号',
          dataIndex: 'noneSpec',
        },
        {
          title: '包材类别',
          dataIndex: 'packageType',
        },
        {
          title: '材质',
          dataIndex: 'materialQuality',
        },
        {
          title: '数量比例',
          dataIndex: 'num',
          scopedSlots: { customRender: 'num' },
          width: 150,
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      labelCol: {
        xs: {span: 24},
        sm: {span: 5},
        style: 'width: 28%;',
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
      textareaLabelCol: {
        xs: {span: 12},
        sm: {span: 2},
      },
      textareaWrapperCol: {
        xs: {span: 40},
        sm: {span: 21},
      },
      confirmLoading: false,
      validatorRules: {
        code: [
          {required: true, message: '请输入编号!'},
        ],
        name: [
          {required: true, message: '请输入名称!'},
        ],
        noneSpec: [
          {required: true, message: '请输入规格!'},
        ],
        // packSpec: [
        //   {required: true, message: '请输入包装规格(g)!'},
        // ],
        categoryCode: [
          {required: true, message: '请输入物料种类!'},
        ],
        customCode: [
          {required: false, message: '请输入客户物料编号!'},
        ],
        meUnit: [
          {required: true, message: '请输入计量单位!'},
        ],
        auUnit: [
          {required: true, message: '请输入辅助单位!'},
        ],
        status: [
          {required: true, message: '请输入状态!'},
        ],
        coRate: [
          {required: true, message: '请输入换算率!'},
        ],
        classificationId: [
          {required: true, message: '请输入物料分类!'},
        ],
        isPattern: [
          {required: false, message: '请输入是否有版样!'},
        ],
        stockQuantity: [
          {required: false, message: '请输入安全库量!'},
        ],
        inventoryQuantity: [
          {required: false, message: '请输入库存数量!'},
        ],
        warehouseCode: [
          {required: true, message: '请输入所属仓库!'},
        ],
        isAssBc: [
          {required: false, message: '请输入是否关联包材!'},
        ],
        isPublic: [
          {required: false, message: '请输入是否公用!'},
        ],
        isUse: [
          {required: false, message: '请输入是否领料!'},
        ],
      },
      url: {
        add: "/base/erpGoods/add",
        edit: "/base/erpGoods/edit",
        queryById: "/base/erpGoods/queryById"
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },
  methods: {
    getSequenceNum() {
      let url = "/sys/fillRule/executeRuleByCode/wlbh";
      putAction(url, {name: "物料编号"}).then(res => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.code = res.result;
        }
      })
    },
    noneSpecChange() {
      try {
        this.model.noneSpec = this.model.noneSpec.toUpperCase().trim();
        let tempSpec = this.model.noneSpec;
        let k = tempSpec.indexOf("KG");
        let k1 = tempSpec.indexOf("G");
        if (k > 0) {
          let c = tempSpec.indexOf("*");
          let t1 = tempSpec.substr(0, k);
          let t2 = tempSpec.substr(c + 1);
          let bt1 = new Big(t1);
          let bt2 = new Big(t2);
          let h = bt1.times(bt2);
          this.model.coRate = h.div(new Big(1000));
        } else if (k1 > 0) {
          let c = tempSpec.indexOf("*");
          let t1 = tempSpec.substr(0, k1);
          let t2 = tempSpec.substr(c + 1);
          let bt1 = new Big(t1);
          let bt2 = new Big(t2);
          let h = bt1.times(bt2);
          this.model.coRate = h.div(new Big(1000000));
        }
      } catch (e) {
      }
    },
    onWarehouseSelected(rows) {
      this.model.warehouseCode = rows.code;
    },
    onGoodsCategorySelected(rows) {
      this.model.categoryCode = rows.code;
      // 判断是否是成品，并且关联包材，如果是下方显示包材关联表
      let str = rows.name;
      let char = "成品";
      let containsChar  = str.includes(char);

      if (containsChar && (this.model.isAssBc === 1 || this.model.isAssBc === '1') ){
        this.showRow = true;
      }else {
        this.showRow = false;
      }
    },
    onChangeShowRow(){
      getAction('/goods/erpGoodsCategory/queryByCode', {code:this.model.categoryCode}).then(res => {
        let str = res.result.name;
        let char = "成品";
        let containsChar  = str.includes(char);
        console.log(containsChar)
        console.log(this.model.isAssBc)
        if (containsChar && (this.model.isAssBc === 1 || this.model.isAssBc === '1' )){

          this.showRow = true;
          console.log("1")
          console.log(this.showRow)
        }else {
          this.showRow = false;
          console.log("2")
          console.log(this.showRow)
        }
      })

    },
    handleSwitchChange(newValue) {
      // newValue 是开关的新值
      console.log('开关的新值:', newValue);
      // 在这里调用你的方法或者进行其他操作
      if (newValue){
        this.getSequenceNum();
      }
    },
    add() {
      this.edit(this.modelDefault);

    },
    edit(record) {
      this.model = Object.assign({}, record);
      this.visible = true;
      this.$refs.selectGoodsCategory.textVals = this.model.categoryCodeText;
      this.$refs.erpWarehouse.textVals = this.model.warehouseCodeText;
      getAction('/base/erpGoods/queryErpGoodsPackageByMainId', {goodsId:this.model.id}).then(res => {
        this.model.erpGoodsPackageList = res.result;
      })
      this.onChangeShowRow();
    },
    submitForm() {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!this.model.id) {
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
          }
          httpAction(httpurl, this.model, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok');
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        }
      })
    },
    // addRowCustom () {
    //   this.orderMainModel.jeecgOrderCustomerList.push({});
    //   this.$forceUpdate();
    // },
    goodsOk(datas) {
      let _this = this;
      postAction('/base/erpGoods/list/ids', { ids: datas }).then(res => {
        console.log(res.result)
        let erpGoodsList = res.result;
        erpGoodsList.forEach(function(item,index){
          console.log(item,index)
          let detail = {};
          detail.packageId = item.id;
          detail.packageCode = item.code;
          detail.packageName = item.name;
          detail.noneSpec = item.noneSpec;
          detail.packageType = item.packageType;
          detail.materialQuality = item.materialQuality;
          console.log(_this.model.erpGoodsPackageList)
          _this.filterPackageId(item.id);
          _this.model.erpGoodsPackageList.push(detail);
        })
      })
    },
    filterPackageId(packageId){
      this.model.erpGoodsPackageList = this.model.erpGoodsPackageList.filter(function(item) {
        return item.packageId !== packageId;
      });
    },
    addMaterielPackage: function(){
      // 新增物料
      // console.log(this.$refs.selectGoodsList)
      this.$nextTick(()=>{
        this.$refs.selectGoodsList.add();
      })
      // this.$refs.selectGoodsList.add();
      // this.$refs.selectGoodsList.title = "新增";
      // this.$refs.selectGoodsList.disableSubmit = false;
    },
    onCellChange(record, dataIndex, value) {
      console.log(this.model.erpGoodsPackageList)
      console.log(record)
      const dataSource = [...this.model.erpGoodsPackageList];
      const target = dataSource.find(item => item.packageCode === record.packageCode);
      // console.log(target,key,dataIndex,value)
      if (record) {
        target[dataIndex] = value;
        this.model.erpGoodsPackageList = dataSource;
      }
    },
    onDelete(key){
      const dataSource = [...this.model.erpGoodsPackageList];
      this.model.erpGoodsPackageList = dataSource.filter(item => item.packageId !== key);
      // deleteAction('base/erpGoodsFormulaDetail/delete',{id:key}).then(res=>{
      //   if(res.success){
      //
      //   }
      // })

    },
  }
}
</script>